define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    function debounce(handle, delay) {
        let time = null;
        return function () {
            let self = this,
                arg = arguments;
            clearTimeout(time);
            time = setTimeout(function () {
                handle.apply(self, arg);
            }, delay)
        }
    }

    var Controller = {
        index: function () {
            var groupIndex = new Vue({
                el: "#htmlIndex",
                data() {
                    return {
                        tableAjax: false,
                        data: [],
                        screenType: false,
                        orderScreenList: {},
                        orderList: [],
                        currentPage: 1,
                        totalPage: 0,
                        offset: 0,
                        limit: 10,
                        // form搜索
                        searchForm: {
                            id: '',
                            user_id: '',
                            native_place: '',
                            address: '',
                            work_unit: '',
                            linkman: '',
                            linkman_phone: '',
                            work_type: '',
                            createtime: [],
                            updatetime: [],
                            id_card: '',
                            date_birth: '',
                            id_card_front: '',
                            id_card_back: '',
                            education: '',
                            sign: ''
                        },
                        searchFormInit: {
                            id: '',
                            user_id: '',
                            native_place: '',
                            address: '',
                            work_unit: '',
                            linkman: '',
                            linkman_phone: '',
                            work_type: '',
                            createtime: [],
                            updatetime: [],
                            id_card: '',
                            date_birth: '',
                            id_card_front: '',
                            id_card_back: '',
                            education: '',
                            sign: ''
                        },
                        searchOp: {
                            id: '=',
                            user_id: '=',
                            native_place: 'LIKE',
                            address: 'LIKE',
                            work_unit: 'LIKE',
                            linkman: 'LIKE',
                            linkman_phone: 'LIKE',
                            work_type: '=',
                            createtime: 'range',
                            updatetime: 'range',
                            id_card: 'LIKE',
                            date_birth: '=',
                            id_card_front: 'LIKE',
                            id_card_back: 'LIKE',
                            education: 'LIKE',
                            sign: 'LIKE'
                        },
                        /**时间快捷选取，可删除**/
                        pickerOptions: {
                            shortcuts: [{
                                text: '今天',
                                onClick(picker) {
                                    const start = moment(new Date()).format('YYYY-MM-DD') + ' 00:00:00';
                                    const end = moment(new Date()).format('YYYY-MM-DD') + ' 23:59:59';
                                    picker.$emit('pick', [start, end]);
                                }
                            }, {
                                text: '昨天',
                                onClick(picker) {
                                    const start = moment(new Date()).add(-1, 'days').format('YYYY-MM-DD') + ' 00:00:00';
                                    const end = moment(new Date()).add(-1, 'days').format('YYYY-MM-DD') + ' 23:59:59';
                                    picker.$emit('pick', [start, end]);
                                }
                            }, {
                                text: '最近一周',
                                onClick(picker) {
                                    const end = moment(new Date()).format('YYYY-MM-DD') + ' 23:59:59';
                                    const start = moment(new Date()).add(-7, 'days').format('YYYY-MM-DD') + ' 00:00:00';
                                    picker.$emit('pick', [start, end]);
                                }
                            }, {
                                text: '最近一个月',
                                onClick(picker) {
                                    const end = moment(new Date()).format('YYYY-MM-DD') + ' 23:59:59';
                                    const start = moment(new Date()).add(-30, 'days').format('YYYY-MM-DD') + ' 00:00:00';
                                    picker.$emit('pick', [start, end]);
                                }
                            }, {
                                text: '上月',
                                onClick(picker) {
                                    const end = moment().month(moment().month() - 1).endOf('month').format('YYYY-MM-DD') + ' 23:59:59';
                                    const start = moment().month(moment().month() - 1).startOf('month').format('YYYY-MM-DD') + ' 00:00:00';
                                    picker.$emit('pick', [start, end]);
                                }
                            }]
                        },
                        Userlimit: 6,
                        Useroffset: 0,
                        currentUserPage: 1,
                        totalUserPage: 0,
                        UsersearchPage: "",
                        aboutUserOptions: [],
                        loading:false,

                    }
                },
                created() {
                    this.reqOrderList();
                    this.getUser();
                },
                methods: {
                    //主键及所有数字类型字段排序，你也可以在html中设置其他自定义字段为排序字段
                    sortChange(column) {
                        this.sort = column.prop;
                        this.order = (column.order == 'ascending' ? 'asc' : 'desc');
                        this.reqOrderList();
                    },
                    //重构fastadmin的ajax方法，以便截取接口返回编码
                    ajax(options, success, error) {
                        options = typeof options === 'string' ? {url: options} : options;
                        var index;
                        if (typeof options.loading === 'undefined' || options.loading) {
                            index = Layer.load(options.loading || 0);
                        }
                        options = $.extend({
                            type: "POST",
                            dataType: "json",
                            xhrFields: {
                                withCredentials: true
                            },
                            success: function (ret) {
                                //兼容官方格式数据
                                var resData = {};
                                resData.data = ret;
                                success.call(this, resData, resData);
                            }
                        }, options);
                        return $.ajax(options);
                    },
                    /**数据交互非通用代码开始**/
                    getUser() {
                        //关联多数据下拉
                        var that = this;
                        that.ajax({
                            url: `user/user/index`,
                            loading: false,
                            type: "GET",
                            data: {
                                limit: that.Userlimit,
                                offset: that.Useroffset,
                                search: that.UsersearchPage,
                                sort: "id" //排序字段，如果您的主键不是ID请自行修改
                            }
                        }, function (ret, res) {
                            that.aboutUserOptions = res.data.rows;
                            that.totalUserPage = res.data.total
                            return false;
                        })
                    },
                    changeUser() {
                        this.dataUserFilter("")
                    },
                    UserdebounceFilter: debounce(function () {
                        this.getUser()
                    }, 1000),
                    dataUserFilter(val) {
                        this.UsersearchPage = val;
                        this.Userlimit = 6;
                        this.Useroffset = 0;
                        this.UsercurrentPage = 1;
                        this.UserdebounceFilter();
                    },
                    //分页
                    pageUserSizeChange(val) {
                        this.Useroffset = 0;
                        this.Userlimit = val;
                        this.currentUserPage = 1;
                        this.getUser()
                    },
                    pageUserCurrentChange(val) {
                        this.Useroffset = (val - 1) * 6;
                        this.Userlimit = 6;
                        this.currentUserPage = 1;
                        this.getUser()
                    },
                    /**数据交互非通用代码结束**/

                    //筛选
                    changeSwitch() {
                        this.screenType = !this.screenType;
                    },
                    //清空筛选
                    screenEmpty() {
                        this.searchForm = JSON.parse(JSON.stringify(this.searchFormInit));
                        this.reqOrderList(0, 10);
                    },
                    // 搜索条件显隐
                    changeStoreId(val) {
                        if (val) {
                            this.searchForm.base_id = '0';
                        } else {
                            this.searchForm.base_id = '';
                        }
                    },
                    //搜索条件
                    dataFilter(val) {
                        this.searchWhree = val;
                        this.storeDebounceFilter()
                    },
                    //请求
                    reqOrderList(offset, limit) {
                        var that = this;
                        if (offset == 0 && limit == 10) {
                            that.offset = offset;
                            that.limit = limit;
                        }
                        let filter = {}
                        let op = {}
                        let arratList = []
                        for (key in that.searchForm) {
                            if (Array.isArray(that.searchForm[key]) && that.searchForm[key] && arratList.includes(key)) {
                                that.searchForm[key] = that.searchForm[key].join(',');
                            }
                            if (that.searchForm[key] != '' && that.searchForm[key] != 'all') {
                                filter[key] = that.searchForm[key];
                            }
                            if (that.searchOp[key] == 'range') {
                                if (that.searchForm[key] && that.searchForm[key].length > 0) {
                                    filter[key] = that.searchForm[key].join(' - ');
                                }
                            } else if (key == 'status') {
                                if (that.searchForm[key] != '' && that.searchForm[key] != 'all') {
                                    filter[key] = that.searchForm[key];
                                }
                            }
                        }
                        for (key in filter) {
                            op[key] = that.searchOp[key]
                        }
                        Fast.api.ajax({
                            url: 'users/information/index',
                            loading: true,
                            type: 'GET',
                            data: {
                                filter: JSON.stringify(filter),
                                op: JSON.stringify(op),
                                offset: that.offset,
                                limit: that.limit,
                                sort: that.sort,
                                order: that.order
                            }
                        }, function (ret, res) {
                            that.data = res.data.rows;
                            that.totalPage = res.data.total;
                            that.focusi = false;
                            return false;
                        })
                    },
                    //新窗口打开
                    openNewWindow(url) {
                        window.open(Fast.api.cdnurl(url), '_blank');
                    },
                    //操作列，可自定义添加事件
                    baseAction(type, id) {
                        let that = this;
                        switch (type) {
                            case 'create':
                                Fast.api.open('users/information/add', '新建', {
                                    callback() {
                                        that.reqOrderList();
                                    }
                                })
                                break;
                            case 'edit':
                                Fast.api.open('users/information/edit?ids=' + id, '编辑', {
                                    callback() {
                                        that.reqOrderList();
                                    }
                                })
                                break;
                            case 'del':
                                that.$confirm('此操作将永久直接删除数据, 是否继续?', '提示', {
                                    confirmButtonText: '确定',
                                    cancelButtonText: '取消',
                                    type: 'warning'
                                }).then(() => {
                                    Fast.api.ajax({
                                        url: 'users/information/del/ids/' + id,
                                        loading: true,
                                        type: 'POST',
                                    }, function (ret, res) {
                                        that.reqOrderList();

                                    })
                                    return false;
                                }).catch(() => {
                                    that.$message({
                                        type: 'info',
                                        message: '已取消删除'
                                    });
                                });
                                break;
                            case 'recyclebin':
                                Fast.api.open('users/information/recyclebin?ids=' + id, '回收站', {
                                    callback() {
                                        that.reqOrderList();
                                    }
                                });
                                break;
                            case 'export':
                                this.loading = true
                                Fast.api.ajax({
                                    url: 'users/information/export',
                                    loading: true,
                                    type: 'POST',
                                    data: {
                                        id:id
                                    }
                                }, function (ret, res) {

                                    let url = res.url;
                                    var currentUrl = window.location.host;
                                    console.log(currentUrl)
                                    let fileUrl = currentUrl+url;
                                    console.log(fileUrl)
                                    // window.location.href = fileUrl
                                    window.open('http://'+fileUrl)
                                    that.$message({
                                        type: 'success',
                                        message: '导出成功'
                                    });
                                    that.loading = false
                                })
                                break;
                        }
                    },
                    handleSizeChange(val) {
                        this.offset = 0
                        this.limit = val;
                        this.currentPage = 1;
                        this.reqOrderList()
                    },
                    handleCurrentChange(val) {
                        this.currentPage = val;
                        this.offset = (val - 1) * this.limit;
                        this.reqOrderList()
                    },
                    tableRowClassName({
                                          rowIndex
                                      }) {
                        if (rowIndex % 2 == 1) {
                            return 'bg-color';
                        }
                        return '';
                    },
                    tableCellClassName({
                                           columnIndex
                                       }) {
                        if (columnIndex == 1 || columnIndex == 4) {
                            return 'cell-left';
                        }
                        return '';
                    },

                },

            })
        },
        add: function () {
            Controller.detailInit('add');
        },
        edit: function () {
            Controller.detailInit('edit');
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        },
        detailInit: function (type) {
            Vue.directive('enterNumber', {
                inserted: function (el) {
                    let changeValue = (el, type) => {
                        const e = document.createEvent('HTMLEvents')
                        e.initEvent(type, true, true)
                        el.dispatchEvent(e)
                    }
                    el.addEventListener("keyup", function (e) {
                        let input = e.target;
                        let reg = new RegExp('^((?:(?:[1-9]{1}\\d*)|(?:[0]{1}))(?:\\.(?:\\d){0,2})?)(?:\\d*)?$');
                        let matchRes = input.value.match(reg);
                        if (matchRes === null) {
                            input.value = "";
                        } else {
                            if (matchRes[1] !== matchRes[0]) {
                                input.value = matchRes[1];
                            }
                        }
                        changeValue(input, 'input')
                    });
                }
            });

            function debounce(handle, delay) {
                let time = null;
                return function () {
                    let self = this,
                        arg = arguments;
                    clearTimeout(time);
                    time = setTimeout(function () {
                        handle.apply(self, arg);
                    }, delay)
                }
            }

            var baseDetail = new Vue({
                el: "#formDetail",
                data() {
                    return {
                        opttype: type,
                        baseFrom: {},
                        rules: {
                            //默认全部列出，根据业务需求删减即可
                            id: [{
                                required: true,
                                message: "请设置" + __('Id'),
                                trigger: "blur"
                            }],

                            user_id: [{
                                required: true,
                                message: "请选择" + __('User'),
                                trigger: "blur"
                            }],

                            native_place: [{
                                required: true,
                                message: "请设置" + __('Native_place'),
                                trigger: "blur"
                            }],

                            address: [{
                                required: true,
                                message: "请设置" + __('Address'),
                                trigger: "blur"
                            }],

                            work_unit: [{
                                required: true,
                                message: "请设置" + __('Work_unit'),
                                trigger: "blur"
                            }],

                            linkman: [{
                                required: true,
                                message: "请设置" + __('Linkman'),
                                trigger: "blur"
                            }],

                            linkman_phone: [{
                                required: true,
                                message: "请设置" + __('Linkman_phone'),
                                trigger: "blur"
                            }],

                            work_type: [{
                                required: true,
                                message: "请设置" + __('Work_type'),
                                trigger: "blur"
                            }],

                            createtime: [{
                                required: true,
                                message: "请设置" + __('Createtime'),
                                trigger: "blur"
                            }],

                            updatetime: [{
                                required: true,
                                message: "请设置" + __('Updatetime'),
                                trigger: "blur"
                            }],

                            id_card: [{
                                required: true,
                                message: "请设置" + __('Id_card'),
                                trigger: "blur"
                            }],

                            date_birth: [{
                                required: true,
                                message: "请设置" + __('Date_birth'),
                                trigger: "blur"
                            }],

                            id_card_front: [{
                                required: true,
                                message: "请设置" + __('Id_card_front'),
                                trigger: "blur"
                            }],

                            id_card_back: [{
                                required: true,
                                message: "请设置" + __('Id_card_back'),
                                trigger: "blur"
                            }],

                            education: [{
                                required: true,
                                message: "请设置" + __('Education'),
                                trigger: "blur"
                            }],

                            sign: [{
                                required: true,
                                message: "请设置" + __('Sign'),
                                trigger: "blur"
                            }],
                        },
                        baseFromInit: {
                            work_type: 0,

                            date_birth: 0,
                        },
                        id: Config.row ? Config.row.id : null,

                        base_address_arr: ['province_name', 'city_name', 'area_name'],
                        base_address_id_arr: ['province_id', 'city_id', 'area_id'],
                        Userlimit: 6,
                        Useroffset: 0,
                        currentUserPage: 1,
                        totalUserPage: 0,
                        UsersearchPage: "",
                        aboutUserOptions: [],
                    }
                },
                mounted() {
                    Controller.api.bindevent();
                    if (this.opttype == 'add') {
                        this.baseFrom = JSON.parse(JSON.stringify(this.baseFromInit));
                    } else {
                        //赋值
                        this.baseFrom = Config.row;
                        this.base_id = Config.row.id;
                        let arratList = []
                        arratList.forEach(field => {
                            if (this.baseFrom[field]) {
                                this.baseFrom[field] = this.baseFrom[field].split(',');
                            }
                        })
                        let jsonList = []
                        jsonList.forEach(field => {
                            this.baseFrom[field] = JSON.parse(this.baseFrom[field]);
                        })
                        let dateFormat = [];
                        dateFormat.forEach(field => {
                            if (this.baseFrom[field].toString().length > 4) {
                                this.baseFrom[field] = moment(this.baseFrom[field] * 1000).format('YYYY-MM-DD HH:mm:ss');
                            } else {
                                this.baseFrom[field] = moment(this.baseFrom[field] + '').format('YYYY-MM-DD HH:mm:ss');
                            }
                        })
                    }
                    this.getUser();
                },
                computed: {
                    isAddImage: function () {
                        return this.timeData.images_arr.length;
                    },
                    isAddress: function () {
                        if (this.baseFrom.base_address) {
                            return this.baseFrom.base_address.length;
                        }
                    },
                },
                methods: {
                    ajax(options, success, error) {

                        options = typeof options === 'string' ? {url: options} : options;
                        var index;
                        if (typeof options.loading === 'undefined' || options.loading) {
                            index = Layer.load(options.loading || 0);
                        }
                        options = $.extend({
                            type: "POST",
                            dataType: "json",
                            xhrFields: {
                                withCredentials: true
                            },
                            success: function (ret) {
                                //兼容官方格式数据
                                var resData = {};
                                resData.data = ret;
                                success.call(this, resData, resData);
                            }
                        }, options);
                        return $.ajax(options);
                    },
                    /**数据交互非通用代码开始**/
                    getUser() {
                        //关联多数据下拉
                        var that = this;
                        that.ajax({
                            url: `user/user/index`,
                            loading: false,
                            type: "GET",
                            data: {
                                limit: that.Userlimit,
                                offset: that.Useroffset,
                                search: that.UsersearchPage,
                                sort: "id" //排序字段，如果您的主键不是ID请自行修改
                            }
                        }, function (ret, res) {
                            that.aboutUserOptions = res.data.rows;
                            that.totalUserPage = res.data.total
                            return false;
                        })
                    },
                    changeUser() {
                        this.dataUserFilter("")
                    },
                    UserdebounceFilter: debounce(function () {
                        this.getUser()
                    }, 1000),
                    dataUserFilter(val) {
                        this.UsersearchPage = val;
                        this.Userlimit = 6;
                        this.Useroffset = 0;
                        this.UsercurrentPage = 1;
                        this.UserdebounceFilter();
                    },
                    //分页
                    pageUserSizeChange(val) {
                        this.Useroffset = 0;
                        this.Userlimit = val;
                        this.currentUserPage = 1;
                        this.getUser()
                    },
                    pageUserCurrentChange(val) {
                        this.Useroffset = (val - 1) * 6;
                        this.Userlimit = 6;
                        this.currentUserPage = 1;
                        this.getUser()
                    },
                    /**数据交互非通用代码结束**/
                    /**通用代码开始，触发函数，不触发则不运行，不占用响应速度，碍事可以删掉**/
                    addImg(type, index, multiple, field, mimetype) {
                        let that = this;
                        parent.Fast.api.open("general/attachment/select?mimetype=" + mimetype + "&multiple=" + multiple, "选择图片", {
                            callback: function (data) {
                                switch (type) {
                                    case "image":
                                        that.baseFrom[field] = data.url;
                                        break;
                                    case "images":
                                        that.baseFrom[field] = that.baseFrom[field].length > 0 ? that.baseFrom[field] + ',' + data.url : data.url;
                                        let arrs = that.baseFrom[field].split(',');
                                        that.baseFrom[field] = arrs;
                                        return;
                                        if (arrs.length > 9) {
                                            that.baseFrom[field] = arrs.slice(-9)
                                        } else {
                                            that.baseFrom[field] = arrs
                                        }
                                        break;
                                }
                            }
                        });
                        return false;
                    },
                    delImg(type, index, field) {
                        let that = this;
                        switch (type) {
                            case "image":
                                that.baseFrom[field] = '';
                                break;
                            case "images":
                                that.baseFrom[field].splice(index, 1);
                                break;
                        }
                    },
                    /**通用代码结束**/
                    baseSub(type, issub) {
                        let that = this;
                        /**提交前需要格式化的数据集中处理开始**/
                        editorList = [];
                        editorList.forEach(field => {
                            that.baseFrom[field] = $("#base-" + field).val();
                        })
                        yearList = [];
                        yearList.forEach(field => {
                            that.baseFrom[field] = moment(this.baseFrom[field]).format('YYYY');
                        })
                        let subDateFormat = [];
                        subDateFormat.forEach(field => {
                            that.baseFrom[field] = moment(this.baseFrom[field]).format('YYYY-MM-DD HH:mm:ss');
                        })
                        let dateArrFormat = [];
                        dateArrFormat.forEach(field => {
                            that.baseFrom[field][0] = moment(that.baseFrom[field][0]).format('YYYY-MM-DD HH:mm:ss');
                            that.baseFrom[field][1] = moment(that.baseFrom[field][1]).format('YYYY-MM-DD HH:mm:ss');
                        })
                        /**提交前需要格式化的数据集中处理结束**/
                        if (type == 'yes') {
                            this.$refs[issub].validate((valid) => {
                                if (valid) {
                                    let subData = JSON.parse(JSON.stringify(that.baseFrom));
                                    //此处可以添加自定义逻辑用以验证提交的数据
                                    if (that.opttype != 'add') {
                                        Fast.api.ajax({
                                            url: 'users/information/edit?ids=' + that.base_id,
                                            loading: true,
                                            type: "POST",
                                            data: {
                                                data: JSON.stringify(subData)
                                            }
                                        }, function (ret, res) {
                                            Fast.api.close({
                                                data: true
                                            })
                                        })
                                    } else {
                                        Fast.api.ajax({
                                            url: 'users/information/add',
                                            loading: true,
                                            type: "POST",
                                            data: {
                                                data: JSON.stringify(subData)
                                            }
                                        }, function (ret, res) {
                                            Fast.api.close({
                                                data: true
                                            })
                                        })
                                    }
                                } else {
                                    return false;
                                }
                            });
                        } else {
                            Fast.api.close({data: false})
                        }
                    },
                },
            })
        },
    };
    return Controller;
});
